package com.zbcz.erp.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.zbcz.erp.bean.BusinessListBean
import com.zbcz.erp.databinding.ItemBusinessTripApplyListBinding
import com.zbcz.erp.util.onSingleClick

class BusinessListAdapter :
    ListAdapter<BusinessListBean, BusinessListAdapter.BusinessListHolder>(BusinessListDiffCallback()) {

    private var fullList = listOf<BusinessListBean>()

    inner class BusinessListHolder(val mBinding: ItemBusinessTripApplyListBinding) :
        RecyclerView.ViewHolder(mBinding.root) {

        init {
            mBinding.cbTop.onSingleClick {
                val mData = currentList.toMutableList()
                for (i in mData.indices) {
                    mData[i] = mData[i].copy(isSelected = i == adapterPosition)
                }
                submitList(mData)
            }
        }

        fun bind() {
            val item = currentList[adapterPosition]
            mBinding.cbTop.isSelected = item.isSelected
            mBinding.cbTop.text = item.title
        }
    }

    class BusinessListDiffCallback : DiffUtil.ItemCallback<BusinessListBean>() {
        override fun areItemsTheSame(oldItem: BusinessListBean, newItem: BusinessListBean): Boolean {
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(oldItem: BusinessListBean, newItem: BusinessListBean): Boolean {
            return oldItem.id == newItem.id && oldItem.isSelected == newItem.isSelected && oldItem.title == newItem.title
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BusinessListHolder {
        val binding = ItemBusinessTripApplyListBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return BusinessListHolder(binding)
    }

    override fun onBindViewHolder(holder: BusinessListHolder, position: Int) {
        holder.bind()
    }

    // 更新列表数据并保存完整列表
    override fun submitList(list: List<BusinessListBean>?) {
        fullList = list ?: listOf()
        super.submitList(list)
    }

    // 添加搜索功能
    fun filterByTitle(query: String) {
        val filteredList = fullList.filter { it.title?.contains(query, ignoreCase = true) == true }
        submitList(filteredList)
    }
}
